#include "employeepage.h"
#include "ui_employeepage.h"
#include "customemployeewidget.h"
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlDriver>
#include <QToolButton>

EmployeePage::EmployeePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EmployeePage)
{
    ui->setupUi(this);

    QSqlQuery query;
    query.exec("SELECT \"User\".\"Name\", \"User\".\"Surname\", \"User\".\"Patronymic\", \"User\".\"Phone_number\", \"Role\".\"Value\", \"User\".\"image\" FROM \"User\", \"Role\" WHERE \"User\".\"role_id\" = \"Role\".\"Id\"");
    editprofile = new Editprofile();
    while(query.next())
    {
        auto item = new QListWidgetItem();
        auto widget = new CustomEmployeewidget(this);
        widget->setText(QString(query.value(0).toString()), QString(query.value(1).toString()), QString(query.value(2).toString()), QString(query.value(3).toString()), QString(query.value(4).toString()), QByteArray(query.value(5).toByteArray()));
        item->setSizeHint(widget->sizeHint());
        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item, widget);
    }
    connect(this, &EmployeePage::connectToEdit, editprofile, &Editprofile::editData);
  /*  ui->listWidget->setAcceptDrops(true);
    ui->listWidget->setDragEnabled(true);
    ui->listWidget->setDragDropMode(QAbstractItemView::InternalMove);*/
}

EmployeePage::~EmployeePage()
{
    delete ui;
}

void EmployeePage::updateEmployee(const QString &name, const QString &surname, const QString &patronymic, const QString &number, const QString &role)
{
    for (int i = 0; i < ui->listWidget->count(); ++i) {
        auto item = ui->listWidget->item(i);
        auto itemWidget = dynamic_cast<CustomEmployeewidget*>(ui->listWidget->itemWidget(item));
        if (itemWidget->getText() == name){
            emit connectToEdit(name, surname, patronymic, number, role);
            break;
        }
    }
}



void EmployeePage::on_AddEmployeeButton_clicked()
{
    emit editpageshow();
}


void EmployeePage::on_updateButton_clicked()
{
    QSqlQuery query;
    query.exec("SELECT \"User\".\"Name\", \"User\".\"Surname\", \"User\".\"Patronymic\", \"User\".\"Phone_number\", \"Role\".\"Value\", \"User\".\"image\" FROM \"User\", \"Role\" WHERE \"User\".\"role_id\" = \"Role\".\"Id\"");

    ui->listWidget->clear();

    while(query.next())
    {
        auto item = new QListWidgetItem();
        auto widget = new CustomEmployeewidget(this);

        widget->setText(QString(query.value(0).toString()), QString(query.value(1).toString()), QString(query.value(2).toString()), QString(query.value(3).toString()), QString(query.value(4).toString()), QByteArray(query.value(5).toByteArray()));

        item->setSizeHint(widget->sizeHint());

        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item, widget);
    }
}

